package com.ehotting.mqbd.core.sync;

import com.ehotting.eaf.netty.client.TcpClient;
import com.ehotting.mqbd.api.bean.MQDataAble;
import com.ehotting.mqbd.core.manager.AgentLinkManager;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
public class TcpClientMapHelper {

    private volatile boolean isRun = true;



    /**
     * agentId:client
     */
    public static final Map<String, TcpClient> tcpClientMap = new ConcurrentHashMap<>(10);


    public void put(String agentId,TcpClient tcpClient){
        tcpClientMap.put(agentId,tcpClient);
    }

    public TcpClient get(String agentId){
        return tcpClientMap.get(agentId);
    }


    public void shutdownClient(MQDataAble data){
        shutdownClient(data.getAgentId());
    }


    public void shutdownClient(String agentId){
        log.info("Start shutdownClient.");
        log.info("agentId:{}.",agentId);
        TcpClient tcpClient = tcpClientMap.get(agentId);
        if(tcpClient!=null && tcpClient.getChannel()!=null){
            tcpClient.shutdown();
        }
        tcpClientMap.remove(agentId);
        log.info("Finish shutdownClient.");
    }


    public void shutdownClientDelay(String agentId){
        log.info("Start shutdownClientDelay.");
        log.info("agentId:{}.",agentId);
        TcpClient tcpClient = tcpClientMap.get(agentId);
        tcpClientMap.remove(agentId);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(tcpClient!=null && tcpClient.getChannel()!=null){
            tcpClient.shutdown();
        }
        tcpClientMap.remove(agentId);
        log.info("Finish shutdownClient.");
    }



    private void cleanInvalidChannel(){
        Set<Map.Entry<String, TcpClient>> tcpClientList =  tcpClientMap.entrySet();
        for(Map.Entry<String, TcpClient>  entry : tcpClientList){
            TcpClient tcpClient = entry.getValue();
            if(tcpClient.getChannel()==null){
                log.info("TcpClient[{}] channel is null,remove.",entry.getKey());
                tcpClientMap.remove(entry.getKey());
                continue;
            }
            if(!tcpClient.getChannel().isActive()){
                log.info("TcpClient[{}] channel is inActive,remove.",entry.getKey());
                tcpClientMap.remove(entry.getKey());
                tcpClient.shutdown();
            }
        }
    }

    public String getSolverIp(ChannelHandlerContext ctx){
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String solverIp = ipSocket.getHostString();
        log.info("solverIp:{}",solverIp);
        return solverIp;
    }




    /***
     * 3个小时释放内存数据
     */
    public void start(){
        log.info("Start TcpClientMapHelper start.");
        Runnable run = new Runnable(){
            @Override
            public void run() {
                while(isRun){
                    try {
                        Thread.sleep(600 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    cleanInvalidChannel();
                }
            }
        };
        Thread thead = new Thread(run);
        thead.start();
        log.info("Finish TcpClientMapHelper start.");
    }


    public void stop(){
        log.info("Start TcpClientMapHelper stop.");
        isRun = false;
        log.info("Finish TcpClientMapHelper stop.");
    }


}
